package leetcode.datastructure.str;

import java.util.ArrayList;
import java.util.List;

public class Program151ReverseWords {

    public Program151ReverseWords() {
    }

    public String reverseWords(String s) {
        int length = s.length();
        int pre = 0;
        List<String> tmp = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) == ' ') {
                pre++;
                continue;
            }
            if (i + 1 == length) {
                if (pre != i) {
                    tmp.add(s.substring(pre, i + 1));
                    pre = i+1;
                }
            } else {
                if (s.charAt(i + 1) == ' ') {
                    tmp.add(s.substring(pre, i + 1));
                    pre = i+1;
                }
            }
        }
        if (pre != length) {
            tmp.add(s.substring(pre));
        }
        if (tmp.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = tmp.size() - 1; i >= 0; i--) {
            sb.append(tmp.get(i)).append(' ');
        }
        int sbLength = sb.length();
        return sb.deleteCharAt(sbLength - 1).toString();
    }

    public static void main(String[] args) {
        Program151ReverseWords obj = new Program151ReverseWords();

//        System.out.println(obj.reverseWords("a good   example"));
        System.out.println(obj.reverseWords(" asdasd df f"));
    }
}
